/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * schedule.java
 *
 * Created on Oct 2, 2012, 9:15:22 AM
 */
package gui;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Vector;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;

import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import pms.DatePicker;
import pms.Employee;
import pms.Log;
import pms.Manager;
import pms.PayrollAdmin;
import pms.Supervisor;

/**
 *
 * @author moonn52
 */
public class schedule extends javax.swing.JFrame {
	
	private Employee e;
	ArrayList<String> ename = null;
	private boolean changes = false;
	
	private DateTime rangeStart = DateTime.parse("1990-01-01");
	private DateTime rangeEnd = DateTime.parse("2018-01-01");

    /** Creates new form schedule */
    public schedule(Employee e) {
    	this.e = e;
        initComponents();
        employeeSelected(e.getEmployeeID());
        this.setSize(1000,700);
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

    	
    	
        jsplHours = new javax.swing.JScrollPane();
//        jlstHours = new javax.swing.JList();
        jmubNavigation = new javax.swing.JMenuBar();
        jmnuHours = new javax.swing.JMenu();
        jmniChangeDisplayRange = new javax.swing.JMenuItem();
        jmniAddEntry = new javax.swing.JMenuItem();
        jmniRemoveSelected = new javax.swing.JMenuItem();
        jmnuEmployees = new javax.swing.JMenu();
        jmnuWindow = new javax.swing.JMenu();
        jmniRequestTimeOff = new javax.swing.JMenuItem();
        jmniInfo = new javax.swing.JMenuItem();
        jmniAlerts = new javax.swing.JMenuItem();
        jmniPayroll = new javax.swing.JMenuItem();
        jmniManagement = new javax.swing.JMenuItem();
        jmniSubmit = new javax.swing.JMenuItem();
        jmniAddEmployee = new javax.swing.JMenuItem();
        jTable1 = new javax.swing.JTable();
//        jLabel1 = new javax.swing.JLabel();
        
  
            jsplHours.setViewportView(jTable1);

//            jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

//        jlstHours.setDropMode(javax.swing.DropMode.INSERT);
//        jsplHours.setViewportView(jlstHours);

        jmnuHours.setText("Hours");

        jmniChangeDisplayRange.setText("Change Display Range");
        jmniChangeDisplayRange.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeDisplayRange(evt);
            }
        });
        jmnuHours.add(jmniChangeDisplayRange);

        jmniAddEntry.setText("Add Entry");
        jmniAddEntry.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addEntry(evt);
            }
        });
        jmnuHours.add(jmniAddEntry);

        jmniRemoveSelected.setText("Remove Selected");
        jmniRemoveSelected.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeSelected(evt);
            }
        });
        jmnuHours.add(jmniRemoveSelected);
        
        jmniSubmit.setText("Submit");
        jmniSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitHours(evt);
            }
        });
        jmnuHours.add(jmniSubmit);

        jmubNavigation.add(jmnuHours);

        jmnuEmployees.setText("Employees");
        jmubNavigation.add(jmnuEmployees);
        
        ArrayList<Integer> eid = null;
        ename = new ArrayList<String>();
        try {
        	if (e instanceof pms.Supervisor) {
        		eid = ((pms.Supervisor) e).getMinions(ename);
//        		eid = (ArrayList<Integer>) ((pms.Supervisor) e).getMinions();
        		if (eid.contains(e.getEmployeeID())) {
        			eid.remove((Object) e.getEmployeeID());
        			ename.remove(e.getName(e.getEmployeeID()));
        		}
        		if (!eid.contains(e.getEmployeeID())) {
        			eid.add(0, e.getEmployeeID());
					ename.add(0, e.getName(e.getEmployeeID()));
        		}
			} else {
				eid = new ArrayList<Integer>();
				eid.add(e.getEmployeeID());
				ename.add(e.getName(e.getEmployeeID()));
			}
        } catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        Collection<JMenuItem> emp = new ArrayList<JMenuItem>();
        int k = 0;
        try {
        for (final int i : eid) {
        	JMenuItem temp = new JMenuItem();
        	
				temp.setText("" + ename.get(k++));
			
        	temp.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    employeeSelected(i);
                }
            });
        	emp.add(temp);
        }
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        for(JMenuItem i: emp)
        	jmnuEmployees.add(i);
        	

        jmnuWindow.setText("Window");

        jmniRequestTimeOff.setText("Request Time Off");
        jmniRequestTimeOff.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showRequestTimeOff(evt);
            }
        });
        jmnuWindow.add(jmniRequestTimeOff);

        jmniInfo.setText("Info");
        jmniInfo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showInfo(evt);
            }
        });
        jmnuWindow.add(jmniInfo);

        jmniAlerts.setText("Alerts");
        jmniAlerts.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showAlertsWindow(evt);
            }
        });
        jmnuWindow.add(jmniAlerts);

        jmniPayroll.setText("Payroll");
        jmniPayroll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showPayroll(evt);
            }
        });
        jmnuWindow.add(jmniPayroll);

//        jmniManagement.setText("Management Requests");
//        jmniManagement.addActionListener(new java.awt.event.ActionListener() {
//            public void actionPerformed(java.awt.event.ActionEvent evt) {
//                showManagementRequests(evt);
//            }
//        });
//        jmnuWindow.add(jmniManagement);

        jmubNavigation.add(jmnuWindow);

        setJMenuBar(jmubNavigation);
        
        if (e.getPriveligeLevel() > 2)
        {
        jmniAddEmployee.setText("Add Employee");
        jmniAddEmployee.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addEmployee(evt);
            }
        });
        jmnuWindow.add(jmniAddEmployee);
        }
        
        
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jsplHours, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jsplHours, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)
        );
        
        pack();
    }// </editor-fold>

    protected void addEmployee(ActionEvent evt) {
		DateTime start_time = new DateTime();
		String first_name = "";
		String last_name = "";
		String address = "";
		String job_number = "";
		String pay_rate = "";
		String sup_id = "";
		String level_of_access = "";
		
		String login = "";
		String password = "";
		
		
		first_name = JOptionPane.showInputDialog("First Name");
		if (first_name == null || first_name.equals(""))
			return;
		last_name = JOptionPane.showInputDialog("Last Name");
		if (last_name == null ||last_name.equals(""))
			return;
		address = JOptionPane.showInputDialog("Address");
		job_number = JOptionPane.showInputDialog("Job Profile Number");
		if (!isInteger(job_number))
			return;
		pay_rate = JOptionPane.showInputDialog("Pay Rate");
		if (!isDouble(pay_rate))
			return;
		sup_id = JOptionPane.showInputDialog("Supervisor ID");
		if (!isInteger(sup_id))
			return;
		login = JOptionPane.showInputDialog("Login");
		if (login == null || login.equals(""))
			return;
		JPasswordField pwd = new JPasswordField(25);  
	    int n = JOptionPane.showConfirmDialog(null, pwd,"Password",JOptionPane.OK_CANCEL_OPTION);
	    if (n < 0)
	    	return;
	    password = new String(pwd.getPassword());
		if (password.equals(""))
			return;
		level_of_access = JOptionPane.showInputDialog("Level of Access");
		if (level_of_access == null || level_of_access.equals(""))
			return;
		if (e instanceof pms.Manager) {
			Manager k;
			try {
				k = new Manager(e.getEmployeeID());
				k.createNewEmployee(first_name, last_name, address, Integer.parseInt(job_number), Double.parseDouble(pay_rate), 0, start_time, Integer.parseInt(sup_id), login,
						password, Integer.parseInt(level_of_access));
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}

    public boolean isInteger(String input) {
		try {
			Integer.parseInt(input);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public boolean isDouble(String input) {
		try {
			Double.parseDouble(input);
			return true;
		} catch (Exception e) {
			return false;
		}
	}
    
	protected void submitHours(ActionEvent evt) {
		// TODO Auto-generated method stub
		if (e instanceof pms.Supervisor) {
			((pms.Supervisor) e).logRange(rangeStart, rangeEnd, ok, selectedEmp);
		} else {
			e.logRange(rangeStart, rangeEnd, ok);
		}
			
	}

	protected void employeeSelected(int i) {
		changes = false;
    	selectedEmp = i;
		// TODO Auto-generated method stub
//		System.out.println("You clicked " + i);
		
		try {
			if (e instanceof pms.Supervisor) {
				ok = ((pms.Supervisor) e).getHours(i, rangeStart, rangeEnd);
			} else {
				ok = new Vector<Log>();
		
				ok.addAll(e.getHours(rangeStart, rangeEnd));
			}
				// TODO Auto-generated catch block
			
			
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		
		
		//for(Log j : ok)
		//	System.out.println(j.employeeID);
		
		//System.out.println(ok.size());
		
		updateTable();
		
		try {
			this.setTitle(e.getName(i));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

//		jlstHours = new JList(ok);
//		jsplHours.setViewportView(jlstHours);
		
		
	}

	private void addEntry(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
		Log temp = new Log();
		
		
		
		temp.dateEntered = new DateTime();
		temp.employeeID = selectedEmp;
//		temp.
		
		DateTime startDate = new DateTime();
		DateTime endDate = new DateTime();
		String start = "Select Start Date";
		String end = " Select End Date";
		DatePicker dStart = new DatePicker();
		
		
		dStart.buildDatePanel(start, startDate);
		startDate = dStart.getSelectedDate();
		
		DatePicker dEnd = new DatePicker();
		
		
		dStart.buildDatePanel(start, endDate);
		endDate = dEnd.getSelectedDate();
		
		if (startDate.isBefore(endDate)) {
		
		temp.endTime = endDate;
		temp.startTime = startDate;
		
		Duration d = new Duration(temp.startTime, temp.endTime);
		
		temp.hoursWorked = d.getStandardHours() + (d.getStandardMinutes() - d.getStandardHours() * 60) / 60;
		
		ok.add(temp);
		
		changes = true;
		
		updateTable();
		} else {
			JOptionPane.showMessageDialog(null,"Your hour range was zero or negative.");
		}
		
    }

    private void changeDisplayRange(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    	int n = -1;
    	if (changes) {
    		JFrame frame = new JFrame();
    		
    		
    		n = JOptionPane.showConfirmDialog(frame, "You have made changes - do you want to lose them?",
    			    "Changes Made",
    			    JOptionPane.YES_NO_OPTION);
    		
    	}
    	try {
    	if (!changes || n==0 ) {
    		DatePicker d = new DatePicker();
    		DateTime day = new DateTime();
    		d.buildDatePanel("Enter Range Start", day);
    		rangeStart = d.getSelectedDate();
    		d.buildDatePanel("Enter Range End", day);
    		rangeEnd = d.getSelectedDate();
    		
    		if (e instanceof pms.Supervisor) {
					ok = ((pms.Supervisor) e).getHours(selectedEmp, rangeStart, rangeEnd);
				
			} else {
				ok = new Vector<Log>();
		
				ok.addAll(e.getHours(rangeStart, rangeEnd));
			}
    		updateTable();
    	}
    	} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
    }

    private void removeSelected(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    	int[] temp = jTable1.getSelectedRows();
    	for (int i = 0; i < temp.length; ++i)
    		ok.remove(temp[temp.length-i-1]);
    	updateTable();
    	changes = true;
    }
    
    private void updateTable() {
    	String[] headers = { "Date Entered", "Hours Worked", "Start Time", "End Time" };
		String[][] table = new String[ok.size()][4];
    	
		DateTimeFormatter dft = DateTimeFormat.forPattern("yyyy/MM/dd h:mm:ss aa");
		
    	for(int j = 0; j < ok.size(); ++j) {
			table[j][0] = ok.get(j).dateEntered.toString(dft);
			table[j][1] = Double.toString(ok.get(j).hoursWorked);
			table[j][2] = ok.get(j).startTime.toString(dft);
			table[j][3] = ok.get(j).endTime.toString(dft);
		}
			
		jTable1.setModel(new javax.swing.table.DefaultTableModel(
                table,
                headers
            ) {
                boolean[] canEdit = new boolean [] {
                    false, false, false, false
                };

                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
                }
            });
    }

    private void showInfo(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    	new info(e).setVisible(true);
    }

    private void showRequestTimeOff(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    	new RTO(e).setVisible(true);
    }

    private void showAlertsWindow(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    	if (e.getPriveligeLevel() > 0)
    		new Notification(e).setVisible(true);
    	else
    		JOptionPane.showMessageDialog(null,"You don't have permission to view Alerts.");
    }

    private void showPayroll(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    	PayrollAdmin p = null;
    	Manager m = null;
    	if(e.getPriveligeLevel()==2){//change to a payrolladmin
			try {
				p = new PayrollAdmin(e.getEmployeeID());
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				Component frame = null;
				JOptionPane.showMessageDialog((Component) frame,e1.getMessage());
			}
			new Payroll(p).setVisible(true);
		}else if(e.getPriveligeLevel()==3){//change to a manager
    		try {
				m = new Manager(e.getEmployeeID());
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				Component frame = null;
				JOptionPane.showMessageDialog((Component) frame,e1.getMessage());
			}
    		new Payroll(m).setVisible(true);
    	}else{
    		Component frame = null;
			JOptionPane.showMessageDialog((Component) frame,"Insufficient privelige level to perform this action.");
    	}
    }

//    private void showManagementRequests(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
//    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(schedule.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(schedule.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(schedule.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(schedule.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
        
            public void run() {
            	Employee k = null;
            	
            	try {
    				k = new Supervisor("th0r", "THORSMASH");
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
            	
                new schedule(k).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private Vector<Log> ok;
    private javax.swing.JLabel jLabel1;
    private int selectedEmp;
//    private javax.swing.JList jlstHours;
    private javax.swing.JMenuItem jmniAddEntry;
    private javax.swing.JMenuItem jmniAlerts;
    private javax.swing.JMenuItem jmniChangeDisplayRange;
    private javax.swing.JMenuItem jmniInfo;
    private javax.swing.JMenuItem jmniManagement;
    private javax.swing.JMenuItem jmniAddEmployee; 
    private javax.swing.JMenuItem jmniPayroll;
    private javax.swing.JMenuItem jmniRemoveSelected;
    private javax.swing.JMenuItem jmniSubmit;
    private javax.swing.JMenuItem jmniRequestTimeOff;
    private javax.swing.JMenu jmnuEmployees;
    private javax.swing.JMenu jmnuHours;
    private javax.swing.JMenu jmnuWindow;
    private javax.swing.JMenuBar jmubNavigation;
    private javax.swing.JScrollPane jsplHours;
    private javax.swing.JTable jTable1;
    // End of variables declaration
}
